import datetime
import json
import random
import time

from django.template.defaulttags import now
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from user.models import UserModel
from utils.myjwt import jwtweb
from utils.mymessage import send_message
from utils.myredis import redistoll


# Create your views here.
#获取数字验证码成功后发送手机验证码
class SendCode(APIView):
    permission_classes = [AllowAny]

    def generate_code(self):
        """生成随机验证码"""
        return str(random.randint(1000, 9999))

    def send_code(self, phone, code):
        """发送验证码到手机"""
        res = send_message(phone, code, 60)
        return json.loads(res)

    def verify_code(self, phone, code):
        """验证用户输入的验证码"""
        stored_code = redistoll.get_str(phone)
        return stored_code == code if stored_code else False
    #获取数字验证码
    def get(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        if not phone:
            return Response({'msg': '手机号不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        code = self.generate_code()
        redistoll.set_time_str(phone, code, 60)  # 使用手机号作为key
        return Response({'msg': '数字验证码发送成功', 'code': code})

    #发送手机验证码
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')

        if not phone or not code:
            return Response({'msg': '手机号和验证码不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        if self.verify_code(phone, code):
            # 生成新的随机验证码并发送
            new_code = self.generate_code()
            send_result = self.send_code(phone, new_code)
            if send_result["statusCode"] == "000000":
                redistoll.set_time_str(phone, new_code, 60)  # 设置验证码有效期为60秒
                return Response({'msg': '验证码发送成功'})
            else:
                return Response({'msg': send_result['statusMsg']}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'msg': '验证码错误'}, status=status.HTTP_400_BAD_REQUEST)

#手机号验证码登录
class LoginView(APIView):
    # permission_classes = [AllowAny]
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        if redistoll.is_exist(phone):
            if redistoll.get_str(phone) == code:
                user = UserModel.objects.filter(phone=phone).first()
                if user:
                    token = jwtweb.jwt_encode({'userid': user.id, 'phone': phone,'exp': int(time.time()) + 3600})
                    retoken = jwtweb.jwt_encode({'userid': user.id, 'phone': phone,"exp": int(time.time()) + 7200})
                    return Response({'code': 200, 'msg': '登录成功', 'id': user.id,'token': token, 'retoken': retoken})
                else:
                    user = UserModel.objects.create(phone=phone)
                    token = jwtweb.jwt_encode({'userid': user.id, 'phone': phone,'exp': int(time.time()) + 3600})
                    retoken = jwtweb.jwt_encode({'userid': user.id, 'phone': phone,"exp": int(time.time()) + 7200})
                    return Response({'code': 200, 'msg': '登录成功', 'userid': user.id,'token': token, 'retoken': retoken})
        return Response({'code': 400, 'msg': '验证码错误'})

#退出登录
class LogOut(APIView):
    def post(self, request):
        token = request.data.get('token')
        print(token)
        times = jwtweb.jwt_decode(token)
        print(times)
        time1 = times['exp'] - int(time.time())
        print(time1)
        redistoll.set_str(token, time1)
        return Response({'msg': '退出成功', 'code': 200})
